Ext.onReady(function(){

    var keyword_store = new Ext.data.Store({
        autoLoad:{params:{start:0,limit:Ext.PagingToolbar.prototype.pageSize}},
        sortInfo:{field:'word',direction:'ASC'},
        remoteSort:true,
        reader:new Ext.data.JsonReader(jsonReader_config,ImageKeyword),
        proxy:new Ext.data.HttpProxy({
            api: {
                read : 'imagekeyword/get.json',
                create : 'imagekeyword/post.json',
                update: 'imagekeyword/put.json',
                destroy: 'imagekeyword/delete.json'
            }
        }),
        writer: new Ext.data.JsonWriter(jsonWriter_config),
        autoSave: true,
        batch:false,
        listeners:{
            write:function(){
                combo.getStore().reload();
            }
        }
    });
    
    var related_store = new Ext.data.Store({
        sortInfo:{field:'word',direction:'ASC'},
        remoteSort:true,
        url:'imagekeyword/get.json',
        reader:new Ext.data.JsonReader(jsonReader_config,ImageKeyword),
        baseParams:{idsImageKeyword:null,word:null}
    });
    
    function onAddRequestTakeClick(btn, ev) {
        var rt = new ImageKeyword({
            name : ''
        });
        panel_panel1_gridpanel.stopEditing();
        panel_panel1_gridpanel.store.insert(0, rt);
        panel_panel1_gridpanel.startEditing(0, 0);
    };
    
    function onAddRequestAngleClick(btn, ev) {
        var ra = new ImageKeyword({
            name : ''
        });
        panel_panel2_gridpanel.stopEditing();
        panel_panel2_gridpanel.store.insert(0, ra);
        panel_panel2_gridpanel.startEditing(0, 0);
    };
   
    var panel_panel1_gridpanel = new Ext.grid.EditorGridPanel({
        frame:true,
        iconCls:'silk_tag_blue',
        border:true,
        title:'Palabras clave',
        hideHeaders:true,
        loadMask:true,
        //style:{padding:'5px'},
        store:keyword_store,
        tbar:[{
            tooltip:'Nueva palabra clave',
            text:'Nueva',
            iconCls:'silk_add',
            handler: onAddRequestTakeClick
        },'->',{
            xtype:'textfield',
            emptyText:'Ingrese texto para filtrar',
            enableKeyEvents:true,
            listeners:{
                keyup:function(this_,e){
                    keyword_store.setBaseParam('word',this_.getValue());
                    keyword_store.load();
                }
            }
        }],
        bbar:new Ext.PagingToolbar({
            store:keyword_store
        }),
        autoExpandColumn:'word',
        columns:[
            {id:'word',dataIndex:'word',sortable:true,editor:{xtype:'textfield',allowBlank:false}},
            {xtype:'actioncolumn',width:30,items:[{
                tooltip:'Borrar',
                icon:iconPath('delete'),
                handler:function(grid,rowIndex){
                     grid.getStore().removeAt(rowIndex);
                }
            }]}
        ],
        selModel:new Ext.grid.RowSelectionModel({
        	singleSelect:true,
            listeners:{
                selectionchange:function(this_){
                	if (this_.getCount() === 1){
                        related_store.setBaseParam('idsImageKeyword',this_.getSelected().id);
                        related_store.load();
                        panel_panel2_gridpanel.setTitle(panel_panel2_gridpanel.initialConfig.title + ' con ' + this_.getSelected().data.word);
                        panel_panel2_gridpanel.enable();
                	}
                    else {
                        related_store.setBaseParam('idsImageKeyword',null);
                        related_store.removeAll();
                        panel_panel2_gridpanel.setTitle(panel_panel2_gridpanel.initialConfig.title);
                        panel_panel2_gridpanel.disable();
                    }
                }
            }
        }),
        listeners:{
            afteredit:function(e){
            	e.grid.getStore().reload();
            }
        }
    });

    var combo = new Ext.form.ComboBox({
        allowBlank:false,
        valueField:'id',
        displayField:'word',
        mode:'remote',
        typeAhead:true,
        forceSelection:true,
        minChars:0,
        triggerAction:'all',
        queryParam:'word',
        store:new Ext.data.Store({
            sortInfo:{field:'word',direction:'ASC'},
            remoteSort:true,
            url:'imagekeyword/get.json',
            reader:new Ext.data.JsonReader(jsonReader_config,ImageKeyword),
            autoLoad:false,
            baseParams:{start:0,limit:8}
        }),
        listeners:{
            select:function(this_){
                if (this_.gridEditor)
                    this_.triggerBlur();
            }
        }
    });
    
    var panel_panel2_gridpanel = new Ext.grid.EditorGridPanel({
        title:'Palabras clave relacionadas',
        frame:true,
        disabled:true,
        iconCls:'silk_tag_green',
        hideHeaders:true,
        border:true,
        //style:{padding:'5px'},
        tbar:[{
            tooltip:'Nueva palabra clave relacionada',
            text:'Nueva',
            iconCls:'silk_add',
            handler: onAddRequestAngleClick
        },'->',{
            xtype:'textfield',
            emptyText:'Ingrese texto para filtrar',
            enableKeyEvents:true,
            listeners:{
                keyup:function(this_,e){
                	related_store.setBaseParam('word',this_.getValue());
                	related_store.load();
                }
            }
        }],
        bbar:new Ext.PagingToolbar({
            store:related_store
        }),
        selModel:new Ext.grid.RowSelectionModel({
            listeners:{
                beforerowselect:function(){
                	return false;
                }
            }
        }),
        autoExpandColumn:'word',
        columns:[
            {id:'word',dataIndex:'word',sortable:true,editor:combo},
            {xtype:'actioncolumn',width:30,items:[
                {tooltip:'Borrar',icon:iconPath('delete'),handler:function(grid,rowIndex){
                    Ext.Ajax.request({
                        url:'imagekeyword/put.json',
                        params:{
                           id:grid.getStore().baseParams.idsImageKeyword,
                           idsImageKeyword:grid.getStore().getAt(rowIndex).id,
                           add:false
                        },
                        callback:function(){
                            related_store.reload();
                        }
                    })
                }}
            ]}
        ],
        loadMask:true,
        store:related_store,
        listeners:{
            afteredit:function(e){
            	Ext.Ajax.request({
                    url:'imagekeyword/put.json',
                    params:{
                       id:related_store.baseParams.idsImageKeyword,
                       idsImageKeyword:e.record.data.id,
                       add:false
                    },
                    callback:function(){
                        Ext.Ajax.request({
                            url:'imagekeyword/put.json',
                            params:{
                               id:related_store.baseParams.idsImageKeyword,
                               idsImageKeyword:e.value,
                               add:true
                            },
                            callback:function(){
                                related_store.reload();
                            }
                        });
                    }
            	})
                return true;
            }
        }
    });
    
    var panel1 = new Ext.Panel({
        layout:'hbox',
        layoutConfig:{align:'stretch',pack:'start'},
        defaults:{flex:1},
        items:[
            panel_panel1_gridpanel,
            {width:5},
            panel_panel2_gridpanel
        ],
        border:false,
        frame:true,
        bodyStyle:{backgroundColor:'transparent'},
        style:{backgroundColor:'transparent',padding:'0 5px 5px 5px'}
	});
	
	var panel2_grid1_store = new Ext.data.Store({
        reader:new Ext.data.JsonReader(jsonReader_config,ImageBackup),
        sortInfo:{field:'name',direction:'ASC'},
        remoteSort:true,
        baseParams:{name:null},
        autoLoad:{params:{start:0,limit:Ext.PagingToolbar.prototype.pageSize}},
        proxy:new Ext.data.HttpProxy({
            api: {
                read : 'imagebackup/get.json',
                create : 'imagebackup/post.json',
                update: 'imagebackup/put.json',
                destroy: 'imagebackup/delete.json'
            }
        }),
        writer: new Ext.data.JsonWriter(jsonWriter_config),
        autoSave:true,
        batch:false,
        listeners:{
            write:function(store){
                store.reload();
            }
        }
    });
	
    var panel2_grid1 = new Ext.grid.EditorGridPanel({
        frame:true,
        iconCls:'silk_cd',
        border:true,
        title:'Medios de backup',
        hideHeaders:true,
        loadMask:true,
        style:{padding:'5px'},
        store: panel2_grid1_store,
        tbar:[{
            tooltip:'Nuevo medio de backup',
            text:'Nuevo',
            iconCls:'silk_add',
            handler: function(b,e){
                var rt = new ImageBackup({
                    name:''
                });
                panel2_grid1.stopEditing();
                panel2_grid1.getStore().insert(0, rt);
                panel2_grid1.startEditing(0, 0);
            }
        },'->',{
            xtype:'textfield',
            emptyText:'Ingrese texto para filtrar',
            enableKeyEvents:true,
            listeners:{
                keyup:function(this_,e){
                    panel2_grid1.getStore().setBaseParam('name',this_.getValue());
                    panel2_grid1.getStore().reload();
                }
            }
        }],
        bbar:new Ext.PagingToolbar({
            store:panel2_grid1_store
        }),
        autoExpandColumn:'name',
        columns:[
            {id:'name',dataIndex:'name',sortable:true,editor:{xtype:'textfield',allowBlank:false}},
            {xtype:'actioncolumn',width:30,items:[{
                tooltip:'Borrar',
                icon:iconPath('delete'),
                handler:function(grid,rowIndex){
                     grid.getStore().removeAt(rowIndex);
                }
            }]}
        ],
        selModel:new Ext.grid.RowSelectionModel({
            singleSelect:true,
            listeners:{
                beforerowselect:function(){
                    return false;
                }
            }
        })
    });
    
    var panel2_grid2_store = new Ext.data.Store({
        reader:new Ext.data.JsonReader(jsonReader_config,ImageProvider),
        sortInfo:{field:'name',direction:'ASC'},
        remoteSort:true,
        baseParams:{name:null},
        autoLoad:{params:{start:0,limit:Ext.PagingToolbar.prototype.pageSize}},
        proxy:new Ext.data.HttpProxy({
            api: {
                read : 'imageprovider/get.json',
                create : 'imageprovider/post.json',
                update: 'imageprovider/put.json',
                destroy: 'imageprovider/delete.json'
            }
        }),
        writer: new Ext.data.JsonWriter(jsonWriter_config),
        autoSave:true,
        batch:false,
        listeners:{
            write:function(store){
                store.reload();
            }
        }
    });
    
    var panel2_grid2 = new Ext.grid.EditorGridPanel({
        frame:true,
        iconCls:'silk_camera',
        border:true,
        title:'Proveedores',
        hideHeaders:true,
        loadMask:true,
        style:{padding:'5px'},
        store: panel2_grid2_store,
        tbar:[{
            tooltip:'Nuevo medio de backup',
            text:'Nuevo',
            iconCls:'silk_add',
            handler: function(b,e){
                var rt = new ImageBackup({
                    name:''
                });
                panel2_grid2.stopEditing();
                panel2_grid2.getStore().insert(0, rt);
                panel2_grid2.startEditing(0, 0);
            }
        },'->',{
            xtype:'textfield',
            emptyText:'Ingrese texto para filtrar',
            enableKeyEvents:true,
            listeners:{
                keyup:function(this_,e){
                    panel2_grid2.getStore().setBaseParam('name',this_.getValue());
                    panel2_grid2.getStore().reload();
                }
            }
        }],
        bbar:new Ext.PagingToolbar({
            store:panel2_grid2_store
        }),
        autoExpandColumn:'name',
        columns:[
            {id:'name',dataIndex:'name',sortable:true,editor:{xtype:'textfield',allowBlank:false}},
            {xtype:'actioncolumn',width:30,items:[{
                tooltip:'Borrar',
                icon:iconPath('delete'),
                handler:function(grid,rowIndex){
                     grid.getStore().removeAt(rowIndex);
                }
            }]}
        ],
        selModel:new Ext.grid.RowSelectionModel({
            singleSelect:true,
            listeners:{
                beforerowselect:function(){
                    return false;
                }
            }
        })
    });
	
	var panel2 = new Ext.Panel({
        layout:'hbox',
        layoutConfig:{align:'stretch',pack:'start'},
        defaults:{flex:1},
        height:200,
        items:[
            panel2_grid1,
            panel2_grid2
        ],
        border:false,
        bodyStyle:{backgroundColor:'transparent'}
	});
	
    var container = new Ext.Panel({
        renderTo:'container',
        layout:'vbox',
        layoutConfig:{align:'stretch',pack:'start'},
        defaults:{flex:1},
        items:[
            panel1,
            panel2
        ],
        border:false,
        bodyStyle:{backgroundColor:'transparent'},
        style:{backgroundColor:'transparent',padding:'0 5px 5px 5px'}        
    })
	
    function resize(){
        if (!Ext.isEmpty(container)){
            container.setHeight(Ext.get('container').getHeight());
            container.doLayout();
        }
    }
    Ext.EventManager.onDocumentReady(resize);
    Ext.EventManager.onWindowResize(resize);
	
},window,{single: true});
